package com.wrb.customer.controller;

import com.wrb.customer.exception.ServiceException;
import com.wrb.customer.model.Customer;
import com.wrb.customer.response.ResponseCode;
import com.wrb.customer.response.ServerResponse;
import com.wrb.customer.service.CustomerService;
import com.wrb.customer.utils.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author wrb
 * @date 2019/11/25 11:40
 */
@RestController
@RequestMapping("/customer")
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(tags = "用户服务")
public class CustomerController {

	@Autowired
	private CustomerService customerService;

	@RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@ApiOperation(value = "注册")
	public ResponseEntity register(
			@ApiParam(required = true, value = "昵称") @RequestParam(required = true) String nickname,
			@ApiParam(required = true, value = "密码") @RequestParam(required = true) String password,
			@ApiParam(required = true, value = "重复密码") @RequestParam(required = true) String passwordRepeat
	) throws ServiceException {
		if (this.customerService.checkNickname(nickname)) {
			return ServerResponse.error(ResponseCode.NICKNAME_OCCUPIED_ERROR, "昵称已被占用");
		}
		if (!password.equals(passwordRepeat)) {
			return ServerResponse.error(ResponseCode.PASSWORD_REPEAT_ERROR, "两次密码输入不相等");
		}
		Customer customer = new Customer();
		customer.setNickname(nickname);
		customer.setPassword(password);
		customerService.register(customer);
		return ServerResponse.success();
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@ApiOperation(value = "登录")
	public ResponseEntity login(
			@ApiParam(required = true, value = "昵称") @RequestParam(required = true) String nickname,
			@ApiParam(required = true, value = "密码") @RequestParam(required = true) String password
	) {
		Customer customer = this.customerService.selectByNicknameAndPassword(nickname, password);
		if (customer == null) {
			return ServerResponse.error(ResponseCode.LOGIN_ERROR, "昵称或者密码不正确");
		}
		String token = JWTUtils.createCustomerJWT(String.valueOf(customer.getCustomerId()), null);
		return ServerResponse.success(token);
	}
}
